package com.cskaoyan.transfer;

import com.cskaoyan.jdbc.util.JDBCUtils;
import org.omg.SendingContext.RunTime;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/06/02 16:27
 *
 * @author ciggar
 *
 * 转账的案例
 *
 * 事务操作
 */
public class TransferDemo {

    static Connection connection;
    static {
        connection = JDBCUtils.getConnection();
    }

    public static void main(String[] args) throws SQLException {

        Boolean ret = transfer("风华哥", "肖战", 2000);
        if (ret) {
            System.out.println("转账成功！");
        }else {
            System.out.println("转账失败！");
        }

    }



    /**
     * 创建日期：2022/06/02 16:28
     * @param fromName  转账发起人
     * @param toName    转账收益人
     * @param money     转账金额
     * @return java.lang.Boolean
     * @author ciggar
     */
    public static Boolean transfer(String fromName,String toName, Integer money) throws SQLException {


        // 开启事务
        connection.setAutoCommit(false);

        try {

            // 给 fromName 扣钱
            PreparedStatement preparedStatement = connection.prepareStatement("update cskaoyan set money = money - ? where teacher_name = ? and money >= ?");

            // 设值
            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);
            preparedStatement.setInt(3, money);

            // 执行SQL语句
            int effectedRows = preparedStatement.executeUpdate();

            // 判断
            if (effectedRows == 0) {
                throw new RuntimeException("扣钱失败！");
            }

//            int i = 1/0;


            // 给toName加钱
            PreparedStatement preparedStatement2 = connection.prepareStatement("update cskaoyan set money = money + ? where teacher_name = ?");

            // 设值
            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);


            // 执行SQL语句
            int effectedRows2 = preparedStatement2.executeUpdate();

            if (effectedRows2 == 0) {
               throw  new RuntimeException("加钱失败!");
            }

        }catch (Exception ex) {
            ex.printStackTrace();
            connection.rollback();
            return false;

        }
        // 提交事务
        connection.commit();
        return true;
    }
}
